import { QuestionCircleOutlined } from '@ant-design/icons';
import { Space } from 'antd';
import React, { useEffect } from 'react';
import { SelectLang, useModel } from 'umi';
import HeaderSearch from '../HeaderSearch';
import Avatar from './AvatarDropdown';
import styles from './index.less';

import { message } from 'antd';
import dayjs from 'dayjs';
import md5 from 'md5';
import NoticeIconView from '../NoticeIcon';
import { typeList } from 'antd/lib/message';
export type SiderTheme = 'light' | 'dark';
let socket: WebSocket;
const GlobalHeaderRight: React.FC = () => {
  const { initialState } = useModel('@@initialState');

  if (!initialState || !initialState.settings) {
    return null;
  }
  const { currentUser } = initialState || {};
  const { updateOnlineUsers, updateSocket, updateMsgs, msgList, updateTitles, titleList } =
    useModel('chatModel', (model) => ({
      updateSocket: model.updateSocket,
      updateOnlineUsers: model.updateOnlineUsers,
      updateMsgs: model.updateMsgs,
      titleList: model.titleList,
      updateTitles: model.updateTitles,
      msgList: model.msgList,
    }));

  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  ${styles.dark}`;
  }
  useEffect(() => {
    const socketUrl = WS_URL + '/ws/imserver/' + currentUser.name;
    // console.log(currentUser, '---currentUser--');
    // console.log(WS_URL, '---WS_URL--');
    if (typeof WebSocket == 'undefined') {
      console.log('您的浏览器不支持WebSocket');
    } else {
      console.log('您的浏览器支持WebSocket');

      // if (socket != null) {
      //   socket.close();
      //   socket = null;
      // }

      socket = new WebSocket(socketUrl);
      updateSocket(socket);

      socket.onopen = function () {
        console.log('websocket已打开');
      };
      socket.onclose = function (message) {
        console.log('websocket已关闭');
      };
      //发生了错误事件
    }
  }, []);

  useEffect(() => {
    socket.onmessage = function (msg) {
      // console.log(msg,'msg');
      const randomNum = Math.floor(Math.random() * 1000);
      const date = dayjs().unix();
      const result = JSON.parse(msg.data);
      // console.log(result, 'result');

      // 更新在线用户
      // if (result.users !== undefined && result.users !== null) {
      //   const users = result.users.map((item) => {
      //     item.id = item.username;
      //     item.nickname = item.username;
      //     return item;
      //   });
      //   updateOnlineUsers(users);
      // }

      // if (result.from !== undefined && result.from !== null) {
      //   const text = result.text;
      //   const tmpmes = {
      //     _id: md5(`${text}${date}${randomNum}`),
      //     date: date,
      //     to: currentUser.name,
      //     user: {
      //       id: result.from,
      //       // avatar: '//game.gtimg.cn/images/lol/act/a20201103lmpwjl/icon-ht.png',
      //       nickname: result.from,
      //       desc: '这是我的第一条信息',
      //     },
      //     message: { type: 'text', content: result.text },
      //   };
      //   // debugger;
      //   console.log(msgList, tmpmes, '----tmpmes----');
      //   updateMsgs([...msgList, tmpmes]);
      // }

      // if (result.title !== undefined && result.title !== null) {
      //   updateTitles([...titleList, result]);
      // }

      if (result instanceof Array) {
        // 数据格式修改
        const list: any[] = [];
        result.map((item: any, index: any) => {
          list.push({
            id: index,
            avatar: '',
            title: item.moduleName + '-' + item.funcName,
            description: item.notifyDesc,
            // datetime: new Date(item.updateTime).toLocaleString(),
            datetime: item.updateTime,
            type:
              item.notifyType == '通知'
                ? 'notification'
                : item.notifyType == '消息'
                ? 'message'
                : 'event',
            read: false,
            clickClose: true,
          });
        });
        list.sort((a,b)=>{return b.datetime-a.datetime});
        // console.log(list, 'list');
        // updateTitles([...list, ...titleList]);
        updateTitles([...list]);
        // console.log([...list, ...titleList], '[...list, ...titleList]');
      }else{
        const list: any[] = [];
        list.push({
          id: result.id,
          avatar: '',
          title: result.moduleName + '-' + result.funcName,
          description: result.notifyDesc,
          // datetime: new Date(item.updateTime).toLocaleString(),
          datetime: result.updateTime,
          type:
          result.notifyType == '通知'
              ? 'notification'
              : result.notifyType == '消息'
              ? 'message'
              : 'event',
          read: false,
          clickClose: true,
        });
        // console.log(list, 'list');
        // updateTitles([...list, ...titleList]);
        updateTitles([...list]);
        // console.log([...list, ...titleList], '[...list, ...titleList]');
      }
    };

    socket.onerror = function () {
      // todo:websocket不急忙加
      // message.error('消息发送出错重新发送');
    };
  }, [msgList, titleList]);
  return (
    <Space className={className}>
      <HeaderSearch
        className={`${styles.action} ${styles.search}`}
        placeholder="站内搜索"
        defaultValue="umi ui"
        options={
          [
            // { label: <a href="https://umijs.org/zh/guide/umi-ui.html">umi ui</a>, value: 'umi ui' },
            // {
            //   label: <a href="next.ant.design">Ant Design</a>,
            //   value: 'Ant Design',
            // },
            // {
            //   label: <a href="https://protable.ant.design/">Pro Table</a>,
            //   value: 'Pro Table',
            // },
            // {
            //   label: <a href="https://prolayout.ant.design/">Pro Layout</a>,
            //   value: 'Pro Layout',
            // },
          ]
        }
        // onSearch={value => {
        //   console.log('input', value);
        // }}
      />
      <span
        className={styles.action}
        onClick={() => {
          window.open('https://pro.ant.design/docs/getting-started');
        }}
      >
        <QuestionCircleOutlined />
      </span>
      <NoticeIconView />
      <Avatar />
      {/* <SelectLang className={styles.action} /> */}
    </Space>
  );
};
export default GlobalHeaderRight;
